package com.cy.common.security.filter;

import com.cy.common.exception.CommonException;
import com.cy.common.utils.JwtUtils;
import com.cy.mapper.TokenMapper;
import com.cy.mapper.UserMapper;
import com.cy.pojo.LoginUser;
import com.cy.pojo.Token;
import com.cy.pojo.User;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author : 残影
 * @Date: 2022/4/12
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Autowired
    private TokenMapper tokenMapper;
    @Autowired
    private UserMapper userMapper;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {
        Long userId;
        try {
            String jwtToken = request.getHeader("authentication");
            if (StringUtils.isEmpty(jwtToken)) {
                chain.doFilter(request, response);
                return;
            }
            userId = JwtUtils.getUserIdByJwtToken(jwtToken);

        } catch (Exception e) {
            e.printStackTrace();
            throw new CommonException("token解析失败");
        }
        Token token = tokenMapper.selectById(userId);
        if (ObjectUtils.isEmpty(token)){
            chain.doFilter(request, response);
            return;
        }
        User user = userMapper.selectById(token.getId());
        if (ObjectUtils.isNotEmpty(user)) {
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(new LoginUser(user), null, null);
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        }
        chain.doFilter(request, response);
    }
}
